﻿using Admin.Core.Common.Auth;
using Admin.Core.Common.BaseModel;
using FreeSql;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Repository.Base
{
    /// <summary>
    /// 带租户和软删除的仓储基类  yxx
    /// </summary>
    /// <typeparam name="TEntity">继承IEntityTenant的实体</typeparam>
    /// <typeparam name="TKey">主键类型</typeparam>
    public abstract class RepositoryTenantDelBase<TEntity, TKey> : BaseRepository<TEntity, TKey> where TEntity : class, IEntityTenant, IEntitySoftDelete, new()
    {
        private readonly IUser _user;
        public  IBaseRepository<TEntity> baseRepository { get; }
        protected RepositoryTenantDelBase(UnitOfWorkManager uowm, IUser user) : base(uowm.Orm, null, null)
        {
            uowm.Binding(this);
            _user = user;
            baseRepository = Orm.GetGuidRepository<TEntity>(t => t.TenantId == _user.TenantId && t.IsDeleted==false);
        }

        public virtual IBaseRepository<TEntity> GetResp()
        {
            return Orm.GetGuidRepository<TEntity>(t => t.TenantId == _user.TenantId);
        }


        public virtual Task<TDto> GetAsync<TDto>(TKey id)
        {
            return baseRepository.Select.WhereDynamic(id).ToOneAsync<TDto>();
        }

        public virtual Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> exp)
        {
            return baseRepository.Select.Where(exp).ToOneAsync();
        }

        public virtual Task<TDto> GetAsync<TDto>(Expression<Func<TEntity, bool>> exp)
        {
            return baseRepository.Select.Where(exp).ToOneAsync<TDto>();
        }

        public async Task<bool> SoftDeleteAsync(TKey id)
        {
            await baseRepository.UpdateDiy
                .SetDto(new
                {
                    IsDeleted = true,
                    ModifiedUserId = _user.Id,
                    ModifiedUserName = _user.Name
                })
                .WhereDynamic(id)
                .ExecuteAffrowsAsync();
            return true;
        }

        public async Task<bool> SoftDeleteAsync(TKey[] ids)
        {
            await baseRepository.UpdateDiy
                .SetDto(new
                {
                    IsDeleted = true,
                    ModifiedUserId = _user.Id,
                    ModifiedUserName = _user.Name
                })
                .WhereDynamic(ids)
                .ExecuteAffrowsAsync();
            return true;
        }




    }

    /// <summary>
    /// 带租户和软删除的仓储基类
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public abstract class RepositoryTenantDelBase<TEntity> : RepositoryTenantDelBase<TEntity, long> where TEntity : class, IEntityTenant,IEntitySoftDelete, new()
    {
        protected RepositoryTenantDelBase(UnitOfWorkManager uowm, IUser user) : base(uowm, user)
        {
        }
    }
}
